import sys,os,time
import zmq
import json
import logging
import marshal
import inspect
import cPickle
from utils import *
from common.data_struct import *
from api.swift_policy import *
reload(sys)
sys.setdefaultencoding('utf-8')


logging.basicConfig(format="[%(asctime)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S",level=logging.DEBUG)


class UserConsole(object):
	"""docstring for UserConsole"""
	def __init__(self):
		self.context=zmq.Context()
		self.container=self.context.socket(zmq.DEALER)
		self.container.connect("tcp://localhost:5556")
		self.id="root"

	def build_group(self,group_name, guard_ids=None):
		return self.send_msg(TYPE_GROUP_BUILD,group_name,guard_ids)
		
	def remove_group(self,group_name, target_group=None):
		return self.send_msg(TYPE_GROUP_DEL,group_name,target_group)

	def list_group(self):
		return self.send_msg(TYPE_GROUP_LIST)
	
	def add_group_member(self,group_name,guard_ids):
		return self.send_msg(TYPE_GROUP_ADD,group_name,guard_ids)

	def move_guard(self,guard_ids,target_group):
		return self.send_msg(TYPE_GROUP_MOVE,guard_ids,target_group)

	def list_guard(self,group_name=None):
		return self.send_msg(TYPE_GUARD_LIST,group_name)

	def get_guard_info(self,guard_id):
		return self.send_msg(TYPE_GUARD_GET,guard_id)

	def add_policy(self,policies,target_app,target_group=None,target_guard=None):
		return self.send_msg(TYPE_POLICY_ADD,policies,target_app,target_group,target_guard)

	def del_policy(self,policy_id,target_app,target_group=None,target_guard=None):
		return self.send_msg(TYPE_POLICY_DEL,policies,target_app,target_group,target_guard)

	def get_policy_info(self,policy_ids):
		return self.send_msg(TYPE_POLICY_GET,policy_ids)

	def create_user(self,account,usr,pwd):
		return self.send_msg(TYPE_CREATE_USR,account,usr,pwd)

	def update_controller(self,func):
		code=func.func_code
		code_str=marshal.dumps(code)
		args=inspect.getargspec(func)[0]
		tmp={}
		func_id=func.__name__
		tmp[func_id]={}
		tmp[func_id]["code"]=code_str
		tmp[func_id]["args"]=args
		print tmp
		return tmp

	def send_msg(self,mtype,*args):
		msg={}
		msg[MSG_TYPE]=mtype
		msg[MSG_SENDER]=self.id
		msg[MSG_BODY]={}
		if mtype==TYPE_GROUP_LIST:
			pass
		if mtype==TYPE_GUARD_LIST:
			if args[0] !=None:
				msg[MSG_BODY][MSG_TARGET]=args[0]
			else:
				msg[MSG_BODY][MSG_TARGET]="ALL"
		if mtype==TYPE_GROUP_BUILD:
			msg[MSG_BODY][MSG_TARGET]=args[0]
			if args[1]==None:
				t=[""]
			else:
				if type(args[1])==str:
					t=[args[1]]
				elif type(args[1])==list:
					t=args[1]
				else:
					return False
			msg[MSG_BODY]["member"]=t

		if mtype==TYPE_GROUP_ADD:
			msg[MSG_BODY][MSG_TARGET]=args[0]
			if type(args[1])==str:
				t=[args[1]]
			elif type(args[1])==list:
				t=args[1]
			else:
				return False
			msg[MSG_BODY]["member"]=t

		if mtype==TYPE_GROUP_MOVE:
			if type(args[1])==str:
				msg[MSG_BODY][MSG_TARGET]=[args[0]]
			elif type(args[1])==list:
				msg[MSG_BODY][MSG_TARGET]=args[0]
			if args[1]==None:
				return False
			else:
				t=args[1]
			msg[MSG_BODY]["member"]=t

		if mtype==TYPE_GROUP_DEL:
			msg[MSG_BODY][MSG_FROM]=args[0]
			if args[1]==None:
				t=""
			else:
				t=args[1]
			msg[MSG_BODY][MSG_TO]=t
		if mtype==TYPE_GUARD_GET:
			msg[MSG_BODY][MSG_TARGET]=args[0]

		if mtype in (TYPE_POLICY_ADD,TYPE_POLICY_DEL):
			msg[MSG_BODY]["POLICY"]=args[0]
			msg[MSG_BODY]["APPID"]=args[1] #if args[1] else "None"
			msg[MSG_BODY]["GROUPID"]=args[2] #if args[2] else "None"
			msg[MSG_BODY]["GUARDID"]=args[3] #if args[3] else "None"
			print msg

		if mtype==TYPE_CREATE_USR:
			msg[MSG_BODY]=(args[0],args[1],args[2])
			pass

		if mtype in (TYPE_USR_DEBUG,):
			msg[MSG_BODY]={}
	
		self.container.send(json.dumps(msg))
		msg=eval(self.container.recv())
		if msg[MSG_TYPE]==TYEP_REP_OPERS_ERR:
			#print msg
			return False
		#logging.info("Get DEBUG response from controller %s: %s",msg[MSG_SENDER],msg)
		print msg[MSG_BODY]
		return msg[MSG_BODY]

	def send_fake_command(self,mtype,*args):
		msg={}
		msg[MSG_TYPE]=mtype
		msg[MSG_SENDER]="root"
		if mtype in (TYPE_GROUP_LIST,TYPE_GUARD_LIST):
			msg[MSG_BODY]={}
		if mtype in (TYPE_GROUP_BUILD,TYPE_GROUP_ADD,TYPE_GROUP_MOVE):
			msg[MSG_BODY]={}
			msg[MSG_BODY]["name"]=args[0]
			if not args[1]:
				t=[""]
			else:
				t=args[1]
			msg[MSG_BODY]["member"]=t
		print "fake",msg
		return msg

	def my_new(self,msg):
		print "my_new_rule_1"
		pass

	def send_upate(self,func):
		msg={}
		msg[MSG_TYPE]=TYPE_UPDATE_CONTROL
		msg[MSG_SENDER]="root"
		msg[MSG_BODY]=self.update_controller(func)
		msg=cPickle.dumps(msg)
		self.container.send(msg)

	def test(self):
		"""
		msg={}
		msg[MSG_TYPE]=TYPE_USR_DEBUG
		msg[MSG_SENDER]="root"
		self.container.send(json.dumps(msg))

		"""
		self.list_group()
		self.list_guard()
		self.build_group("A")
		self.build_group("B")
		self.build_group("C")
		self.list_group()

		guard_ids=self.list_guard(0).keys()
		print "guard",guard_ids
		self.list_guard("A")
		self.add_group_member("A",guard_ids[0:2])
		self.move_guard(guard_ids[0],"B")
		self.remove_group("A","C")
		self.list_group()
		guard_ids=self.list_guard(0).keys()
		self.get_guard_info(guard_ids[0])

		
		"""
		gs=self.send_command(TYPE_GUARD_LIST)["body"].keys()
		gos=self.send_command(TYPE_GROUP_LIST)["body"].keys()
		l1=len(gs)
		l2=len(gos)

		#print self.send_command(TYPE_GROUP_ADD,gos[2],gs[0:4])
		"""
		"""
		print self.send_command(TYPE_GROUP_LIST)
		print self.send_command(TYPE_GROUP_MOVE,gos[0],gs[0:3])
		print self.send_command(TYPE_GROUP_MOVE,gos[2],gs[2:4])
		print self.send_command(TYPE_GROUP_LIST)
		print self.send_command(TYPE_GROUP_DEL,"3","2")
		print self.send_command(TYPE_GROUP_LIST)
		print self.send_command(TYPE_GUARD_LIST)["body"].keys()
		"""
		"""
		print self.send_command(TYPE_GROUP_LIST)
		print self.send_command(TYPE_GROUP_BUILD,"1",None)
		print self.send_command(TYPE_GROUP_BUILD,"2",None)
		print self.send_command(TYPE_GROUP_BUILD,"3",None)
		print self.send_command(TYPE_GROUP_LIST)
		print self.send_command(TYPE_GROUP_MOVE,"2",['4c14bbf032', '4b4114d032'])
		"""
def handler(meta):
	print "meta type",type(meta)
	print "meta: %s"%(meta)
	print "testeststststststst"

if __name__ == '__main__':
	#a=API.Attr("test")
	"""
	p=Policy("aaa","REST")
	p.subject.name="111"
	p.subject.age=1
	p.subject.time=str(time.time())[2:3]
	p.subject.add_attr("123","123")
	p.action.add_action(Action.ACTION_REST_PUT)
	#p.action.remove_action(Action.ACTION_REST_PUT)
	print p.action.action_list
	c=Condition()
	print dir(c)
	"""
	#p.condition.add_cond(Condition.SYS_TIME,"=",10,"ALLOW",)
	#p.condition.add_str_cond("IF SYS_TIME > 10:PRINT;ALLOW")
	#p.add_condition()
	u=UserConsole()
	res=[]
	a=Subject()
	c=Condition()
	p=Policy("p1")
	r=Resource()
	p.set_attr(Condition,"rate","<=",1.0)
	p.set_attr(Subject, "ip", "in", "0.0.0.0/0")
	p.set_attr(Subject, "user", "==", "test1")
	p.set_act("get")
	p.set_dec("ALLOW")
	res.append(p.p)
	#guard_ids=u.list_guard(0).keys()
	u.add_policy(res,"swift_policy")
	u.create_user("123","123","aaa")
	u.send_upate(handler)
	#u.test()
			
		